package com.example.demo;

import com.example.demo.dto.AddUserRequest;
import com.example.demo.dto.AuthInfo;
import com.example.demo.dto.BaseResponse;
import com.example.demo.enums.RoleEnum;
import com.example.demo.util.EncodeUtil;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import sun.misc.InnocuousThread;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@RestController
public class TestController {

    private static Map<String, String> resourceMap = new ConcurrentHashMap<>();

    private static Map<String, List<String>> userResourceMap = new ConcurrentHashMap<>();


    static {
        // 初始化资源
        resourceMap.put("A", "resource A");
        resourceMap.put("B", "resource B");
        resourceMap.put("C", "resource C");
    }

    private ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("/admin/addUser")
    public String addUser(@RequestBody AddUserRequest request, @RequestHeader("auth") String auth)  {
        AuthInfo authInfo = null;
        try {
            authInfo = getHeaderAuth(auth);
        } catch (Exception e) {
            return e.getMessage();
        }


        if(request == null) {
            return "param cannot be null";
        }
        if(request.getUserId() <= 0) {
            return "userId cannot be null";
        }
        if(request.getEndpoint() == null || request.getEndpoint().size() <= 0) {
            return "endpoint be null";
        }

        if(!authInfo.getRole().trim().equals("admin")) {
            return "current user has no permission";
        }

        // 暂不考虑并发场景

        userResourceMap.put(String.valueOf(request.getUserId()), request.getEndpoint());

        return "adduser success";
    }

    @RequestMapping("/user/{resource}")
    public String getResource(@PathVariable(name = "resource") String resource, @RequestHeader("auth") String auth) {
        AuthInfo authInfo = null;
        try {
            authInfo = getHeaderAuth(auth);
        } catch (Exception e) {
            return e.getMessage();
        }

        if(resource==null || "".equals(resource.trim())) {
            return "resource code cannot be null";
        }

        if(userResourceMap.containsKey(String.valueOf(authInfo.getUserId()))) {
            List<String> resourceList = userResourceMap.get(String.valueOf(authInfo.getUserId()));
            if(resourceList.contains(resource)) {
                return "access success";
            }

            return "resource not found";
        }

        return "user not found";
    }


    private AuthInfo getHeaderAuth(String auth) throws Exception {
        if(auth == null || auth.trim() == "") {
            throw new Exception("header contains no auth info");
        }
        String authStr = EncodeUtil.decode(auth);
        AuthInfo authInfo = null;
        try {
            authInfo = objectMapper.readValue(authStr, AuthInfo.class);
            if(authInfo.getUserId() <= 0 || authInfo.getAccountName() == null || authInfo.getAccountName().trim().equals("")
                    || authInfo.getRole()==null || authInfo.getRole().trim().equals("")) {
                throw new Exception("auth param invalid, userId,accountName,role cannot be null");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new Exception("auth is invalid json");
        }

        return authInfo;
    }


}
